#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author : gao
# Time : 2020/7/7 19:24

"""
    文件说明：
"""

import pandas as pd
from sklearn import tree
from sklearn.preprocessing import OneHotEncoder,LabelEncoder
import matplotlib.pyplot as plt
import CreateTree as ct
import PlotTree as pt
import TestTree as tt

def loadData(path):
    with open(path, 'r') as fr:  # 加载文件
        lenses = [inst.strip().split('\t') for inst in fr.readlines()]  # 处理文件
    lenses_target = []  # 提取每组数据的类别，保存在列表里
    for each in lenses:
        lenses_target.append(each[-1])
    print(lenses_target)

    lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate']  # 特征标签
    lenses_list = []  # 保存lenses数据的临时列表
    lenses_dict = {}  # 保存lenses数据的字典，用于生成pandas
    for each_label in lensesLabels:  # 提取信息，生成字典
        for each in lenses:
            lenses_list.append(each[lensesLabels.index(each_label)])
        lenses_dict[each_label] = lenses_list
        lenses_list = []
    print('lenses_dict: ____start___')
    print(lenses_dict)                                              #打印字典信息
    print('lenses_dict: ____end___')
    lenses_pd = pd.DataFrame(lenses_dict)  # 生成pandas.DataFrame
    print('lenses_pd: ____start___')
    print(lenses_pd)  # 打印字典信息
    print('lenses_pd: ____end___')                                                #打印pandas.DataFrame
    le = LabelEncoder()  # 创建LabelEncoder()对象，用于序列化
    for col in lenses_pd.columns:  # 序列化
        lenses_pd[col] = le.fit_transform(lenses_pd[col])
    print('lenses_pd: ____start___')
    print(lenses_pd)
    print('lenses_pd: ____end___')
    return lenses_pd.values.tolist(),lenses_target

def createClassify(X,Y):
    clf = tree.DecisionTreeClassifier(criterion='entropy')
    clf.fit(X,Y)
    return clf

if __name__ =='__main__':
    path = r'C:/Users/gao/Desktop/Machine-Learning-in-Action-master/Machine-Learning-in-Action-master/机器学习实战数据集/Ch03-DecisionTree/lenses.txt'
    trainX,trainY=loadData(path)

    #测试数据集
    dataTest = [[0,1,1,1],[2,1,0,0],[0,1,0,0],[0,1,0,1]]

    clf=createClassify(trainX,trainY)
    tree.plot_tree(clf)
    #plt.show()
    resultSK=clf.predict(dataTest)

    index =0
    for row in trainX:
        row.append(trainY[index])
        index+=1
    lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate']  # 特征标签
    labelsCopy = lensesLabels
    myTree = ct.createDecisionTree(trainX,lensesLabels,[])
    pt.createPlot(myTree)
    resultMine=[]
    for d in dataTest:
        resulsD = tt.classifyByTree(myTree,labelsCopy,d)
        resultMine.append(resulsD)
    print('sk: ', resultSK)
    print('mine：', resultMine)